package com.eltsistemas.dao;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Order;

public class GenericDao<T> {
	
	private Session session;
	private Class<T> classe;
	
	public GenericDao(Session session, Class<T> classe)
	{
		this.session=session;
		this.classe=classe;
	}
	
	public Session adiciona(T t) throws HibernateException
	{
		session.save(t);
		return session;
	}
	
	@SuppressWarnings("unchecked")
	public List<T> listAllByAsc() throws HibernateException
	{
		return session.createCriteria(classe).addOrder(Order.asc("id")).list();
	}
	
	@SuppressWarnings("unchecked")
	public List<T> listAllByDesc() throws HibernateException
	{
		return session.createCriteria(classe).addOrder(Order.desc("id")).list();
	}

	@SuppressWarnings("unchecked")
	public List<T> listaByIdFuncionario(Long id_Funcionario)
	{
		Query query = this.session.createQuery("from "+classe.getSimpleName()+" "+
												"where id_funcionario = :id_funcionario order by id desc");
		query.setLong("id_funcionario", id_Funcionario);
		return query.list();
	}
	
	public List<T> listAllByNome()
	{
		Query query = this.session.createQuery("FROM "+classe.getSimpleName()+" order by nome asc");
		return query.list();		
	}
	
	@SuppressWarnings("unchecked")
	public T findById(Long id)
	{  
		Query query = this.session.createQuery("from "+classe.getSimpleName()+" "+
												"where id = :id");
		query.setLong("id", id);
		return (T) query.uniqueResult();
    }
	
	@SuppressWarnings("unchecked")
	public T findByName(String nome)
	{
		Query query = this.session.createQuery("from "+classe.getSimpleName()+" "+
												"where nome = :nome");
		query.setString("nome", nome);
		return (T) query.uniqueResult();		
	}
	@SuppressWarnings("unchecked")
	public T findByName_ForUpdate(String nome, Long id)
	{
		Query query = this.session.createQuery("from "+classe.getSimpleName()+" "+
												"where nome = :nome and id != :id");
		query.setString("nome", nome);
		query.setLong("id", id);
		return (T) query.uniqueResult();		
	}
	
	public Session altera(T t) throws HibernateException
	{
		session.update(t);
		return session;
	}
	
	public Session remover(T t) throws HibernateException
	{
		session.delete(t);
		return session;
	}
	
}
